from django.conf import settings
from django.http import JsonResponse
from django.shortcuts import redirect
from django.views import View
from fdfs_client.client import Fdfs_client
from rest_framework import status
from rest_framework.response import Response

from users.models import User


class UploadAvatarView(View):
    """上传图片"""
    def post(self, request):
        # 提取数据
        img_bin = request.FILES.get("img").read()

        # 创建FastDFS连接对象
        client = Fdfs_client(settings.FDFS_CLIENT_CONF)
        # 上传图片到fastDFS
        res = client.upload_by_buffer(img_bin)

        if res['Status'] != 'Upload successed.':
            return Response(status=status.HTTP_403_FORBIDDEN)

        # 获取上传后的路径
        image_url = settings.FDFS_URL + res['Remote file_id']
        print(image_url)

        # 保存图片
        # img = User.objects.filter(id=request.user.id).update(avatar=image_url)

        return JsonResponse({'imgurl': image_url}, status=status.HTTP_201_CREATED)


class UploadCommonView(View):
    """上传图片"""

    def post(self, request):
        # 提取数据
        img_bin = request.FILES.get("upload").read()

        # 创建FastDFS连接对象
        client = Fdfs_client(settings.FDFS_CLIENT_CONF)
        # 上传图片到fastDFS
        res = client.upload_by_buffer(img_bin)

        if res['Status'] != 'Upload successed.':
            return Response(status=status.HTTP_403_FORBIDDEN)

        # 获取上传后的路径
        image_url = settings.FDFS_URL + res['Remote file_id']
        # print(image_url)

        # 保存图片
        # img = User.objects.filter(id=request.user.id).update(avatar=image_url)

        url = settings.CALLBACK_IMG_URL + image_url

        return redirect(url)
